// 文件路径: src/main/java/com/chixing/service/impl/TransactionServiceImpl.java

package com.chixing.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chixing.config.AlipayConfig;
import com.chixing.controller.WebSocketProcess;
import com.chixing.entity.OrderBase;
import com.chixing.entity.OrderDetail;
import com.chixing.entity.Transaction;
import com.chixing.entity.UserCoupon;
import com.chixing.mapper.TransactionMapper;
import com.chixing.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chixing.util.Result;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.alipay.api.AlipayConstants.SIGN_TYPE;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liwenjing
 * @since 2025-10-07
 */
@Service
public class TransactionServiceImpl extends ServiceImpl<TransactionMapper, Transaction> implements ITransactionService {
    @Autowired
    private TransactionMapper transactionMapper;

    @Autowired
    private IOrderBaseService orderBaseService;
    @Autowired
    private IOrderDetailService orderDetailService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ICouponService couponService;
    @Autowired
    private IUserCouponService userCouponService;
    @Autowired
    private SeatStatusService seatStatusService;
    @Autowired
    private WebSocketProcess webSocketProcess;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result handlePaymentSuccess(Integer orderId, Integer userId, BigDecimal paymentAmount, String alipayTradeNo) {
        // 1. 查询订单信息
        OrderBase orderBase = orderBaseService.getOrderById(orderId);
        if (orderBase == null) {
            return Result.error("订单不存在");
        }
        try {
            // 2. 确认座位预订状态（永久锁定）
            boolean seatConfirmResult = seatStatusService.confirmBookingPermanently(
                    orderBase.getScheduleId(),
                    orderBase.getSeatCoordinates()
            );

            if (!seatConfirmResult) {
                throw new RuntimeException("座位确认失败");
            }
            // 2. 创建交易流水
            Transaction transaction = new Transaction();
            transaction.setTransactionNumber(UUID.randomUUID().toString().replace("-", "")); // 生成唯一流水号
            transaction.setOrderId(orderId);
            transaction.setPaymentAmount(paymentAmount);
            transaction.setStatues(1); // 1-支付成功
            transaction.setCreateTime(LocalDateTime.now());
            transaction.setUpdateTime(LocalDateTime.now());
            transaction.setVersion(1);
            transaction.setOther1(alipayTradeNo); // 存储支付宝交易号
            boolean saveResult = save(transaction);
            if (!saveResult) {
                return Result.error("创建交易流水失败");
            }

            // 3. 更新订单状态为"已支付"（假设1为已支付状态）
            orderBase.setStatues(1);
            orderBase.setUpdateTime(LocalDateTime.now());
            boolean updateOrderResult = orderBaseService.updateOrder(orderBase);
            if (!updateOrderResult) {
                throw new RuntimeException("更新订单状态失败"); // 触发事务回滚
            }
            //同时需要更新订单详情的状态
            QueryWrapper<OrderDetail> detailWrapper = new QueryWrapper<>();
            detailWrapper.eq("order_id", orderId);
            OrderDetail updateDetail = new OrderDetail();
            updateDetail.setStatues(1); // 1表示已支付
            updateDetail.setUpdateTime(LocalDateTime.now());
            orderDetailService.update(updateDetail, detailWrapper);
            // 4. 如果使用了优惠券，更新优惠券状态为"已使用"
            Integer userCouponId = orderBase.getUserCouponId();
            if (userCouponId != null) {
                UserCoupon userCoupon = userCouponService.getUserCouponById(userCouponId);
                if (userCoupon != null && userCoupon.getStatues() == 1) {
                    userCoupon.setStatues(0); // 0-已使用
                    userCoupon.setUpdateTime(LocalDateTime.now());
                    boolean updateCouponResult = userCouponService.updateUserCoupon(userCoupon);
                    if (!updateCouponResult) {
                        throw new RuntimeException("更新优惠券状态失败"); // 触发事务回滚
                    }
                }
            }
            rabbitTemplate.setMessageConverter(new Jackson2JsonMessageConverter());

            // 支付成功后推送消息
            Map<String, Object> messageData = new HashMap<>();
            messageData.put("userId", userId);
            messageData.put("message", "已经完成购票，请及时观影");
            messageData.put("orderId", orderId);
            messageData.put("timestamp", LocalDateTime.now());

            // 发送到消息队列，由专门的消息处理器消费
            rabbitTemplate.convertAndSend("notification_exchange", "ticket.purchased", messageData);
            String message = "已经完成购票，请及时观影";
            webSocketProcess.sendMessage(Long.valueOf(userId), message);

            return Result.getSuccess(transaction);
        } catch (Exception e) {
            throw new RuntimeException("支付处理失败: " + e.getMessage(), e);
        }
    }
    @Override
    public List<Transaction> getAllTransactions() {
        return list();
    }

    @Override
    public Transaction getTransactionById(Integer transactionId) {
        return getById(transactionId);
    }


    @Override
    public boolean addTransaction(Transaction transaction) {
        return save(transaction);
    }

    @Override
    public boolean updateTransaction(Transaction transaction) {
        return updateById(transaction);
    }

    @Override
    public boolean deleteTransaction(Integer transactionId) {
        return removeById(transactionId);
    }
    // TransactionServiceImpl.java
    @Override
    public Transaction getTransactionByOrderId(Integer orderId) {
        // 查询订单对应的交易流水
        QueryWrapper<Transaction> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_id", orderId);

        return transactionMapper.selectOne(queryWrapper);
    }


}

